#include <vector>
using namespace std;
/*
 * @lc app=leetcode.cn id=80 lang=cpp
 *
 * [80] 删除有序数组中的重复项 II
 */

// @lc code=start
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int l = -1, r = 0, last, times = 0;
        while (r < nums.size()) {
            if (!r || last != nums[r]) {
                last = nums[r]; times = 1; l++;
                swap(nums[l], nums[r]);
            } 
            else if (last == nums[r] && times < 2) {
                times++; l++;
                swap(nums[l], nums[r]);
            }
            r++;
        }
        return l + 1;
    }

    void swap(int & x, int & y) {
        int t = x;
        x = y;
        y = x;
    }
};
// @lc code=end

